<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import CharacterSelection from '../components/naruto/CharacterSelection.vue';
import BattleSystem from '../components/naruto/BattleSystem.vue';
import GameHeader from '../components/naruto/GameHeader.vue';
import GameFooter from '../components/naruto/GameFooter.vue';
import AudioService from '../services/AudioService';

// 游戏状态
const gameState = ref('characterSelection'); // characterSelection, battle, result
const selectedCharacter = ref(null);
const opponentCharacter = ref(null);
const showInstructions = ref(false); // 是否显示游戏说明

// 可用角色列表
const availableCharacters = ref([
  {
    id: 1,
    name: '鸣人',
    description: '木叶村的漩涡鸣人，九尾人柱力',
    image: '/naruto/naruto.svg',
    health: 120,
    chakra: 100,
    strength: 85,
    skills: ['螺旋丸', '影分身之术', '仙人模式']
  },
  {
    id: 2,
    name: '佐助',
    description: '宇智波佐助，复仇者',
    image: '/naruto/sasuke.svg',
    health: 110,
    chakra: 95,
    strength: 88,
    skills: ['千鸟', '豪火球之术', '写轮眼']
  },
  {
    id: 3,
    name: '小樱',
    description: '春野樱，医疗忍者',
    image: '/naruto/sakura.svg',
    health: 90,
    chakra: 90,
    strength: 75,
    skills: ['樱花冲', '医疗忍术', '怪力']
  },
  {
    id: 4,
    name: '卡卡西',
    description: '旗木卡卡西，拷贝忍者',
    image: '/naruto/kakashi.svg',
    health: 120,
    chakra: 100,
    strength: 90,
    skills: ['雷切', '写轮眼', '千年杀']
  },
  // S级忍者 - 三忍
  {
    id: 5,
    name: '纲手',
    description: '木叶三忍之一，第五代火影',
    image: '/naruto/tsunade.svg',
    health: 140,
    chakra: 110,
    strength: 95,
    skills: ['樱花冲', '创造再生', '百豪之术']
  },
  {
    id: 6,
    name: '大蛇丸',
    description: '木叶三忍之一，禁忌的科学家',
    image: '/naruto/orochimaru.svg',
    health: 130,
    chakra: 120,
    strength: 92,
    skills: ['秽土转生', '八岐之术', '蛇蜕皮']
  },
  {
    id: 7,
    name: '自来也',
    description: '木叶三忍之一，传说中的三忍',
    image: '/naruto/jiraiya.svg',
    health: 135,
    chakra: 115,
    strength: 94,
    skills: ['螺旋丸', '仙人模式', '仙法·超大玉螺旋丸']
  },
  // 晓组织成员
  {
    id: 8,
    name: '鼬',
    description: '晓组织成员，宇智波鼬',
    image: '/naruto/itachi.svg',
    health: 125,
    chakra: 110,
    strength: 96,
    skills: ['月读', '天照', '须佐能乎']
  },
  {
    id: 9,
    name: '鬼鲛',
    description: '晓组织成员，干柿鬼鲛',
    image: '/naruto/kisame.svg',
    health: 150,
    chakra: 105,
    strength: 98,
    skills: ['鲛肌融合', '大鲛弹之术', '水遁·爆水冲波']
  },
  {
    id: 10,
    name: '佩恩',
    description: '晓组织首领，六道佩恩',
    image: '/naruto/pain.svg',
    health: 145,
    chakra: 130,
    strength: 97,
    skills: ['神罗天征', '地爆天星', '万象天引']
  }
]);

// 选择角色后的处理函数
const handleCharacterSelect = (character) => {
  if (!character) {
    console.error('无效的角色选择');
    return;
  }
  
  selectedCharacter.value = character;
  
  // 随机选择一个对手角色，确保不是玩家选择的同一个
  let availableOpponents = availableCharacters.value.filter(char => char.id !== character.id);
  
  if (availableOpponents.length === 0) {
    // 极端情况下的错误处理
    console.warn('没有可用的对手角色，使用相同角色');
    opponentCharacter.value = { ...character };
  } else {
    opponentCharacter.value = availableOpponents[Math.floor(Math.random() * availableOpponents.length)];
  }
  
  // 进入战斗状态
  gameState.value = 'battle';
};

// 获取随机对手
const getRandomOpponent = () => {
  const opponents = [
    { id: 2, name: '佐助', image: '/naruto/sasuke.png', health: 100, chakra: 80, strength: 85, skills: ['千鸟', '豪火球之术', '写轮眼'] },
    { id: 3, name: '小樱', image: '/naruto/sakura.png', health: 90, chakra: 90, strength: 75, skills: ['樱花冲', '医疗忍术', '怪力'] },
    { id: 4, name: '卡卡西', image: '/naruto/kakashi.png', health: 120, chakra: 100, strength: 90, skills: ['雷切', '写轮眼', '千年杀'] },
    { id: 5, name: '鸣人(九尾模式)', image: '/naruto/naruto_kyubi.png', health: 150, chakra: 120, strength: 95, skills: ['螺旋手里剑', '尾兽玉', '九尾查克拉模式'] }
  ];
  return opponents[Math.floor(Math.random() * opponents.length)];
};

// 处理战斗结束
const handleBattleEnd = (result) => {
  console.log('战斗结果:', result);
  gameState.value = 'result';
};

// 重新开始游戏
const restartGame = () => {
  try {
    // 清理战斗状态
    gameState.value = 'characterSelection';
    selectedCharacter.value = null;
    opponentCharacter.value = null;
    
    // 重置游戏说明显示状态
    showInstructions.value = false;
    
    // 重置音效状态
    try {
      AudioService.clearAllSounds();
      AudioService.playBackgroundMusic();
    } catch (audioError) {
      console.warn('重置音效时出错:', audioError);
    }
  } catch (error) {
    console.error('重新开始游戏时出错:', error);
    // 即使出错也要尝试恢复到初始状态
    gameState.value = 'characterSelection';
  }
};

// 切换游戏说明显示
const toggleInstructions = () => {
  showInstructions.value = !showInstructions.value;
};
</script>

<template>
  <div class="naruto-game naruto-container">
    <GameHeader />
    
    <main class="game-content">
      <!-- 游戏说明按钮 -->
      <button @click="toggleInstructions" class="instructions-button naruto-button">
        {{ showInstructions ? '隐藏游戏说明' : '游戏说明' }}
      </button>
      
      <!-- 游戏说明面板 -->
      <div v-if="showInstructions" class="instructions-panel naruto-card">
        <h3>火影忍者对战游戏说明</h3>
        <ul>
          <li>1. 选择一名你喜欢的火影忍者作为你的角色</li>
          <li>2. 系统将随机为你分配一个对手</li>
          <li>3. 在战斗中，你可以选择普通攻击或使用消耗查克拉的技能</li>
          <li>4. 每名忍者都有自己独特的技能和属性</li>
          <li>5. 击败对手即可获得胜利</li>
        </ul>
      </div>
      
      <div v-if="gameState === 'characterSelection'" class="character-selection-container naruto-card">
        <h2>选择你的忍者</h2>
        <p class="selection-intro">请从以下忍者中选择一名作为你的角色，每个忍者都有不同的属性和技能组合。</p>
        <CharacterSelection @character-select="handleCharacterSelect" :available-characters="availableCharacters" />
      </div>
      
      <div v-else-if="gameState === 'battle'" class="battle-container naruto-card">
        <h2>战斗开始!</h2>
        <BattleSystem 
          :player="selectedCharacter" 
          :opponent="opponentCharacter" 
          @battle-end="handleBattleEnd" 
        />
      </div>
      
      <div v-else-if="gameState === 'result'" class="result-container naruto-card">
        <h2>战斗结束!</h2>
        <div class="result-message">
          <p v-if="selectedCharacter && opponentCharacter">
            {{ selectedCharacter.name }} vs {{ opponentCharacter.name }}
          </p>
          <p>感谢参与火影忍者战斗!</p>
        </div>
        <button @click="restartGame" class="restart-button naruto-button">重新开始</button>
      </div>
    </main>
    
    <GameFooter />
  </div>
</template>

<style scoped>
.naruto-game {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  color: var(--naruto-black);
  font-family: 'Arial', 'Microsoft YaHei', sans-serif;
}

.game-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 2rem;
  gap: 1.5rem;
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
}

.character-selection-container,
.battle-container,
.result-container,
.instructions-panel {
  width: 100%;
  max-width: 800px;
  margin-bottom: 1rem;
  animation: fadeIn 0.5s ease-in-out;
  background-color: rgba(255, 255, 255, 0.9);
  border: 2px solid var(--naruto-orange);
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

h2 {
  text-align: center;
  margin-bottom: 1.5rem;
  font-size: 2.2rem;
  color: var(--naruto-red);
  font-weight: bold;
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.1);
}

h3 {
  color: var(--naruto-red);
  margin-bottom: 1rem;
}

.selection-intro {
  text-align: center;
  margin-bottom: 2rem;
  font-size: 1.1rem;
  color: var(--naruto-black);
}

.instructions-button {
  position: absolute;
  top: 20px;
  right: 20px;
  z-index: 10;
}

.instructions-panel {
  position: absolute;
  top: 80px;
  right: 20px;
  width: 300px;
  z-index: 10;
  max-height: 80vh;
  overflow-y: auto;
}

.instructions-panel ul {
  padding-left: 1.5rem;
}

.instructions-panel li {
  margin-bottom: 0.5rem;
}

.result-message {
  text-align: center;
  font-size: 1.5rem;
  margin: 2rem 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .game-content {
    padding: 1rem;
  }
  
  h2 {
    font-size: 1.8rem;
  }
  
  .instructions-button {
    position: relative;
    top: 0;
    right: 0;
    width: 100%;
    margin-bottom: 1rem;
  }
  
  .instructions-panel {
    position: relative;
    top: 0;
    right: 0;
    width: 100%;
    max-height: none;
  }
}
</style>